package com.theme.passport.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.theme.common.mvc.view.R;
import com.theme.passport.annotation.Login;
import com.theme.passport.controller.app.utils.AppContextUtil;
import com.theme.passport.entity.UserEntity;
import com.theme.passport.entity.theme.TabActivationCode;
import com.theme.passport.form.ActivationCodeForm;
import com.theme.passport.service.TabActivationCodeService;
import com.theme.passport.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("app/tabActivationCode-in")
public class AppTabActivationCodeController {


    @Autowired
    private TabActivationCodeService service;


    @Autowired
    private UserService userService;

    /**
     * 兑换VIP激活码
     */
    @Login
    @PostMapping("/exchange")
    public R exchange(@RequestBody ActivationCodeForm form) {

        UserEntity currentUser = AppContextUtil.getCurrentUser();
        //查询兑换码状态
        TabActivationCode codeEntity = service.getOne(new LambdaQueryWrapper<TabActivationCode>()
                .eq(TabActivationCode::getActivationCode, form.getActivationCode()));
        if(codeEntity == null){
            return R.error("无效的激活码");
        }
        if (codeEntity.getIsUsed().equals("1")) {
            return R.error("激活码已被使用");
        }
        if (codeEntity.getIsUsed().equals("2")) {
            return R.error("激活码已作废");
        }
        codeEntity.setIsUsed("1");
        codeEntity.setUsedTime(new Date());
        codeEntity.setUseUserId(currentUser.getId());
        service.updateById(codeEntity);

        //增加用户VIP时间
        //修改用户为VIP和新增过期时间
        UserEntity user = userService.updateUserVipDays(currentUser.getId(), 7);
        return R.ok("激活成功");
    }




}
